import AsyncStorage from '@react-native-async-storage/async-storage';

class TokenManager {
  private static TOKEN_KEY = 'auth_token';
  private static TOKEN_EXPIRY_KEY = 'token_expiry';
  private static DEFAULT_EXPIRY_DAYS = 30; // 默认30天过期

  // 设置Token
  static async setToken(token: string, expiryDays: number = this.DEFAULT_EXPIRY_DAYS): Promise<void> {
    try {
      const expiryDate = new Date();
      expiryDate.setDate(expiryDate.getDate() + expiryDays);

      await AsyncStorage.setItem(this.TOKEN_KEY, token);
      await AsyncStorage.setItem(this.TOKEN_EXPIRY_KEY, expiryDate.toISOString());
    } catch (error) {
      console.error('TokenManager: Error setting token:', error);
    }
  }

  // 获取Token
  static async getToken(): Promise<string | null> {
    try {
      const token = await AsyncStorage.getItem(this.TOKEN_KEY);
      if (!token) return null;

      // 检查Token是否过期
      if (await this.isTokenExpired()) {
        await this.clearToken();
        return null;
      }

      return token;
    } catch (error) {
      console.error('TokenManager: Error getting token:', error);
      return null;
    }
  }

  // 清除Token
  static async clearToken(): Promise<void> {
    try {
      await AsyncStorage.removeItem(this.TOKEN_KEY);
      await AsyncStorage.removeItem(this.TOKEN_EXPIRY_KEY);
    } catch (error) {
      console.error('TokenManager: Error clearing token:', error);
    }
  }

  // 检查Token是否过期
  static async isTokenExpired(): Promise<boolean> {
    try {
      const expiryDateStr = await AsyncStorage.getItem(this.TOKEN_EXPIRY_KEY);
      if (!expiryDateStr) return true;

      const expiryDate = new Date(expiryDateStr);
      return new Date() > expiryDate;
    } catch (error) {
      console.error('TokenManager: Error checking token expiry:', error);
      return true;
    }
  }

  // 刷新Token
  static async refreshToken(newToken: string, expiryDays: number = this.DEFAULT_EXPIRY_DAYS): Promise<void> {
    await this.setToken(newToken, expiryDays);
  }
}

export default TokenManager;